local skynet = require "skynet"
local util = require "util"
local table_unpack = table.unpack
local table_insert = table.insert
local table_remove = table.remove
local math_random = math.random

local M = {}

local Methods = {}
local MT = {
    __index = Methods
}

function M.new(uid,player_info,robot_type,AI,addr,fd,conf)
    dbglog("new robot:", tostring(uid), tostring_r(player_info))
    local o = {
        uid = uid,
        player_info = player_info,
        robot_type = robot_type,
        AI = AI,
        addr = addr,
        fd = fd,
        conf = conf
    }

    return setmetatable(o, MT)
end

function Methods:on_register()
    local rob_info = {
        client_version  = '',
        channel         = '',
        cur_channel     = '',
        device_id       = '',
        device_brand    = '',
    }

    skynet.send(self.addr,'lua','enter',self.uid,self.fd,rob_info)
    self.ready_time = util.get_now_time() + math_random(3,6)
end

--自己进桌
function Methods:on_enter()
    return
end

local function analyse_rob_dizhu(self)
    if not self.ddz_instance:is_rob_dizhu() then
        return
    end
    if self.ddz_instance:get_setting_uid() == self.uid then
        self.rob_time = util.get_now_time() + math_random(4,5)
        self.rob_request = self.AI.analyse_rob_dizhu(self)
    end
end

local function analyse_play(self)
    if not self.ddz_instance:is_playing() then
        return
    end
    if self.ddz_instance:get_next_player_uid() == self.uid then
        self.play_time = util.get_now_time() + math_random(2,4)
        self.play_request = self.AI.analyse_play(self)
    end
end

local function analyse_jiabei(self)
    if not self.ddz_instance:is_jiabei() then
        return
    end
    self.jiabei_time = util.get_now_time() + math_random(3,5)
    --如果渠道受限则不加倍
    if self.ddz_instance:get_table_pattern() == 4 then
        self.jiabei_request = {type = 0}
    else
        self.jiabei_request = self.AI.analyse_jiabei(self)
    end
end

--游戏开始触发
function Methods:on_start(ddz_instance)
    self.ddz_instance = ddz_instance
    
    analyse_rob_dizhu(self)
end

--抢地主
function Methods:on_rob_dizhu(uid,score,is_rob)
    dbglog('on_rob_dizhu',uid,score,is_rob)
    if uid == self.uid then return end
    analyse_rob_dizhu(self)
end

--加倍
function Methods:on_jiabei()
    dbglog('on_jiabei')
    analyse_jiabei(self)
end

function Methods:on_start_play()
    dbglog('on_start_play')
    analyse_play(self)
    
    if self.is_rob then self.is_rob = false end
end

--出牌
function Methods:on_play(uid,card_id_list)
--    dbglog('on_play ....')
    if uid == self.uid then return end
    analyse_play(self)
end

--游戏结束
function Methods:on_game_over()
    self.ddz_instance = nil
    self.picture_list = nil
    self.last_pic_time = nil
    --下一轮准备
end

--机器人使用表情
function Methods:on_use_picture(uid,pic_conf,is_enter)
    if self.uid ~= uid then return end
    if not pic_conf then
        print(uid,"=====pic_conf is nil ===")
        return
    end 
    local select_pic,delay_time
    if self.ddz_instance then
        select_pic,delay_time = self.ddz_instance:robot_can_use_pic(pic_conf)
    elseif is_enter then    --玩家刚进来时instance可能未初始化
        if math_random(1,100) <= pic_conf.use_rate then
            local use_pic = pic_conf.select_pic 
            select_pic = use_pic[math_random(1,#use_pic)]
            if pic_conf.delay_time and pic_conf.delay_time[1] and pic_conf.delay_time[2] then
                delay_time = math_random(pic_conf.delay_time[1],pic_conf.delay_time[2])
            end
        end 
    end
  
    if select_pic then
        if not delay_time or delay_time < 2 then 
            delay_time = math_random(2,6)     --至少给个2s种的延时吧
        end
        local msg = {
            type = 1,
            picture_id = select_pic,
        }
        if not self.picture_list then
            self.picture_list = {}
        end
        table_insert(self.picture_list,{
            send_time = util.get_now_time() + delay_time,    --每个动作之后，过两秒再发，避免动作和表情包同步，太假
            msg = msg
        }) 
        if self.ddz_instance then
            self.ddz_instance:add_use_pic_num()
        end
    end
end

function Methods:on_restart()
    dbglog('on_restart')
    self.ready_time = util.get_now_time() + math_random(3,6)
end

function Methods:on_nodizhu_restart()
    dbglog('on_nodizhu_restart ...')
    self.ddz_instance = nil
end

function Methods:check_ready(curr_time)
    if not self.ready_time then
        return
    end

    if curr_time >= self.ready_time then
        self.ready_time = nil
        skynet.send(self.addr,'lua','REQ_READY',self.uid,{ready=1},self.fd)
    end
end

function Methods:update_rob_dizhu(curr_time)
    local ddz_instance = self.ddz_instance
    if not ddz_instance:is_rob_dizhu() then
        return
    end
    --轮到自己抢地主
    if ddz_instance:get_setting_uid() == self.uid and 
        self.rob_time and curr_time >= self.rob_time then
        local req_msg = assert(self.rob_request)
        self.rob_request = nil
        self.rob_time = nil
        skynet.send(self.addr,'lua','REQ_ROBDIZHU',self.uid,req_msg,self.fd)
    end
end

function Methods:update_play(curr_time)
    local ddz_instance = self.ddz_instance
    if not ddz_instance:is_playing() then
        return
    end
    --轮到自己出牌
    if ddz_instance:get_next_player_uid() == self.uid and 
        self.play_time and curr_time >= self.play_time then
        local req_msg = assert(self.play_request)
        self.play_request = nil
        self.play_time = nil
        skynet.send(self.addr,'lua','REQ_PLAY',self.uid,req_msg,self.fd)
    end
end

function Methods:update_jiabei(curr_time)
    local ddz_instance = self.ddz_instance
    if not ddz_instance:is_jiabei() then
        return
    end
    if self.jiabei_time and curr_time >= self.jiabei_time then
        local req_msg = assert(self.jiabei_request)
        self.jiabei_request = nil
        self.jiabei_time = nil
        skynet.send(self.addr,'lua','REQ_JIABEI',self.uid,req_msg,self.fd)
    end
end

function Methods:judge_use_pic(curr_time)
    --上一次发表情的时间间隔小于1s，先不发，避免两个表情同步
    if self.last_pic_time and curr_time - self.last_pic_time < 1 then
        return
    end
    local picture_list = self.picture_list
    if picture_list then
        for k = #picture_list,1,-1 do
            local pic_info = picture_list[k]
            if curr_time > pic_info.send_time then
                skynet.send(self.addr,'lua','REQ_CHAT',self.uid,pic_info.msg,self.fd)
                table_remove(self.picture_list,k)
                return
            end
        end
    end
end

function Methods:update()
    while not self.exit do
        local curr_time = util.get_now_time()

        if self.ddz_instance then
            --当前是抢地主？
            self:update_rob_dizhu(curr_time)
            --当前是否加倍？
            self:update_jiabei(curr_time)
            --当前可以出牌？
            self:update_play(curr_time)
        else
            --游戏未开始则需要检查自己是否准备了
            self:check_ready(curr_time)
        end
        self:judge_use_pic(curr_time)
        skynet.sleep(50)    --500ms
    end

    dbglog(self.uid,'exit !!!!')
end

function Methods:on_exit()
    self.exit = true
    print("ddz exit==============")
    R().robotmgr(1):send('.msg_handler','put_back_robots',{{type=self.robot_type,uid=self.uid,coins=self.player_info.coins}})
end

return M
